package com.portal.common.thread.example.part3;

/**
 * 线程安全：都是由全局变量及静态变量引起的
 * 1、若对全局变量及静态变量只有读操作没有写操作，则线程安全；若有写操作，则线程不安全。
 */

class Ticket3 implements Runnable {
    private int ticketNums = 100;

    @Override
    public void run() {
        while (true) {
            sale();
        }
    }

    /**
     * 1、类似对当前代码块加锁，【synchronized(this)】
     * 2、修饰静态方法时，同步监视器是当前类对象，【synchronized(Ticket3.class)】
     */
    public synchronized void sale() {
        if (ticketNums > 0) {
            System.out.println(Thread.currentThread().getName() + "售出一张票，剩余票数为：" + --ticketNums);
        }
    }
}

public class ThreadSafe3 {
    public static void main(String[] args) {
        Ticket3 ticket = new Ticket3();
        Thread window1 = new Thread(ticket, "窗口1");
        Thread window2 = new Thread(ticket, "窗口2");
        Thread window3 = new Thread(ticket, "窗口3");
        window1.start();
        window2.start();
        window3.start();
    }
}
